"""
用户管理API端点
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional

from app.core.database import get_db
from app.core.dependencies import (
    get_current_active_user, require_user_view, require_user_manage
)
from app.models.auth import User
from app.schemas.auth import (
    UserCreate, UserUpdate, UserResponse, UserListResponse
)
from app.schemas.common import BaseResponse
from app.services.permission_service import PermissionService
from app.core.logger import logger

router = APIRouter()
permission_service = PermissionService()


@router.get("", response_model=BaseResponse[UserListResponse])
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    role_id: Optional[int] = Query(None, description="角色ID"),
    is_active: Optional[bool] = Query(None, description="用户状态"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_view)
):
    """
    获取用户列表
    
    - **page**: 页码，从1开始
    - **page_size**: 每页数量，最大100
    - **search**: 搜索用户名、邮箱或姓名
    - **role_id**: 按角色筛选
    - **is_active**: 按状态筛选
    """
    try:
        result = await permission_service.get_user_list(
            db, page, page_size, search, role_id, is_active
        )
        
        return BaseResponse(
            data=result,
            message="获取用户列表成功",
            success=True
        )
    except Exception as e:
        logger.error(f"获取用户列表失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户列表失败"
        )


@router.post("", response_model=BaseResponse[UserResponse])
async def create_user(
    user_data: UserCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_manage)
):
    """
    创建用户
    
    - **username**: 用户名（3-50字符，只允许字母、数字、下划线）
    - **email**: 邮箱地址
    - **password**: 密码（至少8字符，包含大小写字母、数字、特殊字符）
    - **full_name**: 真实姓名（可选）
    - **phone**: 手机号码（可选）
    - **department**: 部门（可选）
    - **position**: 职位（可选）
    - **role_ids**: 角色ID列表
    """
    try:
        result = await permission_service.create_user(db, user_data, current_user)
        
        return BaseResponse(
            data=result,
            message="用户创建成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建用户失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建用户失败"
        )


@router.get("/{user_id}", response_model=BaseResponse[UserResponse])
async def get_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_view)
):
    """
    获取用户详情
    
    - **user_id**: 用户ID
    """
    try:
        from sqlalchemy import select
        from sqlalchemy.orm import selectinload
        
        stmt = select(User).where(User.id == user_id).options(
            selectinload(User.user_roles).selectinload(User.role)
        )
        result = await db.execute(stmt)
        user = result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        return BaseResponse(
            data=UserResponse.from_orm(user),
            message="获取用户详情成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户详情失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户详情失败"
        )


@router.put("/{user_id}", response_model=BaseResponse[UserResponse])
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_manage)
):
    """
    更新用户信息
    
    - **user_id**: 用户ID
    - **email**: 邮箱地址（可选）
    - **full_name**: 真实姓名（可选）
    - **phone**: 手机号码（可选）
    - **department**: 部门（可选）
    - **position**: 职位（可选）
    - **is_active**: 用户状态（可选）
    - **role_ids**: 角色ID列表（可选）
    """
    try:
        result = await permission_service.update_user(db, user_id, user_data, current_user)
        
        return BaseResponse(
            data=result,
            message="用户更新成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新用户失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新用户失败"
        )


@router.delete("/{user_id}", response_model=BaseResponse[dict])
async def delete_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_manage)
):
    """
    删除用户
    
    - **user_id**: 用户ID
    """
    try:
        result = await permission_service.delete_user(db, user_id, current_user)
        
        return BaseResponse(
            data=result,
            message="用户删除成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除用户失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除用户失败"
        )


@router.post("/{user_id}/reset-password", response_model=BaseResponse[dict])
async def reset_user_password(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_user_manage)
):
    """
    重置用户密码
    
    - **user_id**: 用户ID
    """
    try:
        from sqlalchemy import select
        from app.core.security import get_password_hash
        from datetime import datetime
        from app.utils.timezone_utils import get_shanghai_now
        import secrets
        import string
        
        # 查找用户
        stmt = select(User).where(User.id == user_id)
        result = await db.execute(stmt)
        user = result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 生成新密码
        new_password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(12))
        new_password = f"{new_password}A1!"  # 确保符合密码要求
        
        # 更新密码
        user.password_hash = get_password_hash(new_password)
        user.password_changed_at = get_shanghai_now()
        user.updated_at = get_shanghai_now()
        
        await db.commit()
        
        logger.info(f"用户密码重置成功：{user.username} (by {current_user.username})")
        
        return BaseResponse(
            data={
                "message": "密码重置成功",
                "new_password": new_password,
                "username": user.username
            },
            message="密码重置成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"重置用户密码失败：{str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重置密码失败"
        )


@router.get("/me/profile", response_model=BaseResponse[UserResponse])
async def get_my_profile(
    current_user: User = Depends(get_current_active_user)
):
    """
    获取当前用户的个人资料
    """
    try:
        return BaseResponse(
            data=UserResponse.from_orm(current_user),
            message="获取个人资料成功",
            success=True
        )
    except Exception as e:
        logger.error(f"获取个人资料失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取个人资料失败"
        )


@router.put("/me/profile", response_model=BaseResponse[UserResponse])
async def update_my_profile(
    profile_data: UserUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    更新当前用户的个人资料

    注意：用户只能更新自己的基本信息，不能修改角色和状态
    """
    try:
        from datetime import datetime
        from app.utils.timezone_utils import get_shanghai_now
        # 限制用户只能更新特定字段
        allowed_fields = ['email', 'full_name', 'phone', 'department', 'position']
        update_data = profile_data.dict(exclude_unset=True)
        
        # 移除不允许的字段
        filtered_data = {k: v for k, v in update_data.items() if k in allowed_fields}
        
        if not filtered_data:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="没有可更新的字段"
            )
        
        # 检查邮箱是否被其他用户使用
        if 'email' in filtered_data and filtered_data['email'] != current_user.email:
            from sqlalchemy import select, and_
            
            stmt = select(User).where(
                and_(User.email == filtered_data['email'], User.id != current_user.id)
            )
            result = await db.execute(stmt)
            if result.scalar_one_or_none():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已被其他用户使用"
                )
        
        # 更新用户信息
        for field, value in filtered_data.items():
            setattr(current_user, field, value)
        
        current_user.updated_at = get_shanghai_now()
        await db.commit()
        
        logger.info(f"用户更新个人资料成功：{current_user.username}")
        
        return BaseResponse(
            data=UserResponse.from_orm(current_user),
            message="个人资料更新成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新个人资料失败：{str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新个人资料失败"
        )
